package com.ruoyi.face.util;

import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.MetadataException;
import com.drew.metadata.exif.ExifDirectoryBase;
import com.drew.metadata.exif.ExifImageDirectory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

public class ImageUtil {

    public static int GetRotateAngle(InputStream input) throws ImageProcessingException, IOException, MetadataException {
        int angel = 0;
        Metadata metadata = ImageMetadataReader.readMetadata(input);
         Directory directory = metadata.getFirstDirectoryOfType(ExifDirectoryBase.class);
        if (directory != null && directory.containsTag(ExifDirectoryBase.TAG_ORIENTATION)) {
            int orientation = directory.getInt(ExifDirectoryBase.TAG_ORIENTATION);
            if (6 == orientation) {
                angel = 90;
            } else if (3 == orientation) {
                angel = 180;
            } else if (8 == orientation) {
                angel = 270;
            }
        }

        return angel;
    }

    /**
     * 对图片进行旋转
     *
     * @param src   被旋转图片
     * @param angel 旋转角度
     * @return 旋转后的图片
     */
    public static BufferedImage Rotate(Image src, int angel) {
        int srcWidth = src.getWidth(null);
        int srcHeight = src.getHeight(null);
        // 计算旋转后图片的尺寸
        Rectangle rect_des = CalcRotatedSize(new Rectangle(new Dimension(
                srcWidth, srcHeight)), angel);
        BufferedImage res = null;
        res = new BufferedImage(rect_des.width, rect_des.height,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = res.createGraphics();
        // 进行转换
        g2.translate((rect_des.width - srcWidth) / 2,
                (rect_des.height - srcHeight) / 2);
        g2.rotate(Math.toRadians(angel), srcWidth / 2, srcHeight / 2);

        g2.drawImage(src, null, null);
        return res;
    }

    /**
     * 计算旋转后的图片
     *
     * @param src   被旋转的图片
     * @param angel 旋转角度
     * @return 旋转后的图片
     */
    public static Rectangle CalcRotatedSize(Rectangle src, int angel) {
        // 如果旋转的角度大于90度做相应的转换
        if (angel >= 90) {
            if (angel / 90 % 2 == 1) {
                int temp = src.height;
                src.height = src.width;
                src.width = temp;
            }
            angel = angel % 90;
        }

        double r = Math.sqrt(src.height * src.height + src.width * src.width) / 2;
        double len = 2 * Math.sin(Math.toRadians(angel) / 2) * r;
        double angelAlpha = (Math.PI - Math.toRadians(angel)) / 2;
        double angelDeltaWidth = Math.atan((double) src.height / src.width);
        double angelDeltaHeight = Math.atan((double) src.width / src.height);

        int lenDeltaWidth = (int) (len * Math.cos(Math.PI - angelAlpha
                - angelDeltaWidth));
        int lenDeltaHeight = (int) (len * Math.cos(Math.PI - angelAlpha
                - angelDeltaHeight));
        int desWidth = src.width + lenDeltaWidth * 2;
        int desHeight = src.height + lenDeltaHeight * 2;
        return new Rectangle(new Dimension(desWidth, desHeight));
    }

    public static byte[] Resize2Inch(byte[] file) {
        byte[] bytes = file;
        ByteArrayInputStream input = new ByteArrayInputStream(bytes);
        BufferedImage image;
        try {
            int angle = GetRotateAngle(input);
            input.reset();
            image = ImageIO.read(input);
            if (angle > 0) {
                image = Rotate(image, angle);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //2寸 （普通）照片尺寸： 3.5*4.5cm 412*531像素
        float standardWidth = 412;
        float standardHeight = 531;
        if (bytes.length > 512 * 1024) {
            int height = image.getHeight();
            int width = image.getWidth();
            float rate;
            if (width > 412) {
                rate = standardWidth / width;
            } else {
                rate = standardHeight / height;
            }
            int resizeWidth = (int) (width * rate);
            int resizeHeight = (int) (height * rate);

            BufferedImage dist = new BufferedImage(resizeWidth, resizeHeight, BufferedImage.TYPE_INT_RGB);
            dist.getGraphics().drawImage(image.getScaledInstance(resizeWidth, resizeHeight, Image.SCALE_SMOOTH), 0, 0, null);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            try {
                ImageIO.write(dist, "jpg", outputStream);
                bytes = outputStream.toByteArray();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return bytes;
    }
}
